#!/usr/bin/env node

/**
 * 快速性能测试脚本
 * 使用方法: node quick-test.js [并发数] [请求数]
 */

const http = require('http');

const concurrentUsers = parseInt(process.argv[2]) || 50;
const requestsPerUser = parseInt(process.argv[3]) || 5;
const testUrl = 'http://localhost:3000/health';

console.log(`🚀 快速性能测试`);
console.log(`📊 并发用户: ${concurrentUsers}`);
console.log(`📨 每用户请求: ${requestsPerUser}`);
console.log(`🎯 总请求数: ${concurrentUsers * requestsPerUser}`);
console.log(`🔗 测试URL: ${testUrl}`);
console.log('-'.repeat(50));

async function makeRequest() {
  return new Promise((resolve, reject) => {
    const startTime = Date.now();
    
    const req = http.request(testUrl, (res) => {
      let data = '';
      res.on('data', chunk => data += chunk);
      res.on('end', () => {
        const endTime = Date.now();
        resolve({
          statusCode: res.statusCode,
          responseTime: endTime - startTime,
          success: res.statusCode >= 200 && res.statusCode < 300
        });
      });
    });

    req.on('error', (error) => {
      reject({
        error: error.message,
        success: false
      });
    });

    req.setTimeout(10000, () => {
      req.destroy();
      reject({
        error: 'timeout',
        success: false
      });
    });

    req.end();
  });
}

async function runTest() {
  const startTime = Date.now();
  const promises = [];
  
  // 创建所有请求
  for (let i = 0; i < concurrentUsers * requestsPerUser; i++) {
    promises.push(
      makeRequest()
        .then(result => result)
        .catch(error => ({ ...error, success: false }))
    );
  }
  
  // 等待所有请求完成
  console.log('⏳ 执行中...');
  const results = await Promise.all(promises);
  const endTime = Date.now();
  
  // 统计结果
  const successful = results.filter(r => r.success);
  const failed = results.filter(r => !r.success);
  const responseTimes = successful.map(r => r.responseTime);
  
  const totalTime = endTime - startTime;
  const avgResponseTime = responseTimes.length > 0 ? 
    responseTimes.reduce((a, b) => a + b, 0) / responseTimes.length : 0;
  const rps = (results.length / (totalTime / 1000)).toFixed(2);
  
  // 输出结果
  console.log('\n📊 测试结果:');
  console.log(`✅ 成功请求: ${successful.length}`);
  console.log(`❌ 失败请求: ${failed.length}`);
  console.log(`📈 成功率: ${(successful.length / results.length * 100).toFixed(2)}%`);
  console.log(`⏱️  平均响应时间: ${avgResponseTime.toFixed(2)}ms`);
  console.log(`🚀 吞吐量: ${rps} RPS`);
  console.log(`⏳ 总耗时: ${totalTime}ms`);
  
  if (responseTimes.length > 0) {
    console.log(`⚡ 最快响应: ${Math.min(...responseTimes)}ms`);
    console.log(`🐌 最慢响应: ${Math.max(...responseTimes)}ms`);
  }
  
  // 性能评估
  const successRate = successful.length / results.length * 100;
  if (successRate >= 99 && avgResponseTime < 100) {
    console.log('\n🟢 性能评级: 优秀');
  } else if (successRate >= 95 && avgResponseTime < 500) {
    console.log('\n🟡 性能评级: 良好');
  } else if (successRate >= 80) {
    console.log('\n🟠 性能评级: 一般');
  } else {
    console.log('\n🔴 性能评级: 需要优化');
  }
}

runTest().catch(console.error);
